﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using Byond.Standalone.MidiDotNetStuff;
using MidiDotNet;
using Mvvm;
using System.Linq;

namespace Byond.Standalone.ViewModels
{
	internal class MidiSettingsViewModel : ViewModelBase
	{
		private readonly DotNetMidi _dotNetMidi;
		private readonly SettingsManager _settingsManager;

		private void Ctor()
		{
			InputDevice.InstalledDevices.Select(it => new MidiDeviceViewModel(it)).ForEach(_inputDevices.Add);
			_inputDevices.Insert(0, MidiDeviceViewModel.None);
			OutputDevice.InstalledDevices.Select(it => new MidiDeviceViewModel(it)).ForEach(_outputDevices.Add);
			_outputDevices.Insert(0, MidiDeviceViewModel.None);

			SelectedInputDevice = InputDevices.FirstOrDefault(it => it.Device == _dotNetMidi.InputDevice);
			SelectedOutputDevice = OutputDevices.FirstOrDefault(it => it.Device == _dotNetMidi.OutputDevice);
		}

		private readonly ObservableCollection<MidiDeviceViewModel> _inputDevices = new ObservableCollection<MidiDeviceViewModel>();
		public IEnumerable<MidiDeviceViewModel> InputDevices { get { return _inputDevices; } }

		private readonly ObservableCollection<MidiDeviceViewModel> _outputDevices = new ObservableCollection<MidiDeviceViewModel>();
		public IEnumerable<MidiDeviceViewModel> OutputDevices { get { return _outputDevices; } }

		private MidiDeviceViewModel _selectedInputDevice;
		public MidiDeviceViewModel SelectedInputDevice
		{
			get { return _selectedInputDevice; }
			set
			{
				// --None-- als default device
				_selectedInputDevice = value ?? _inputDevices.First();
				OnPropertyChanged("SelectedInputDevice");
			}
		}

		private MidiDeviceViewModel _selectedOutputDevice;
		public MidiDeviceViewModel SelectedOutputDevice
		{
			get { return _selectedOutputDevice; }
			set
			{
				_selectedOutputDevice = value ?? _outputDevices.First();
				OnPropertyChanged("SelectedOutputDevice");
			}
		}

		public void ApplySettings()
		{
			_dotNetMidi.SetInputDevice((InputDevice)SelectedInputDevice.Device);
			_dotNetMidi.SetOutputDevice((OutputDevice)SelectedOutputDevice.Device);

			_settingsManager.UpdateSettings(
				new MidiSettings
					{
						InputDeviceName = SelectedInputDevice.DeviceName,
						OutputDeviceName = SelectedOutputDevice.DeviceName,
					});
		}
	}
}